package xyz.quanguanjia.masterboy.me;

import android.content.Intent;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.basic.PictureSelectionCameraModel;
import com.luck.picture.lib.basic.PictureSelectionSystemModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.HashMap;

import xyz.quanguanjia.masterboy.MBDCompressFileEngine;
import xyz.quanguanjia.masterboy.MBDCropEngine;
import xyz.quanguanjia.masterboy.MBDHostManager;
import xyz.quanguanjia.masterboy.MBDHttpClient;
import xyz.quanguanjia.masterboy.util.MBDImageUtils;
import xyz.quanguanjia.masterboy.MBDModelResponse;
import xyz.quanguanjia.masterboy.MBDToolbarUtils;
import xyz.quanguanjia.masterboy.MBDUserCenter;
import xyz.quanguanjia.masterboy.R;
import xyz.quanguanjia.masterboy.ServiceType;
import xyz.quanguanjia.masterboy.model.MBDAccountInfoModel;
import xyz.quanguanjia.masterboy.util.DensityUtils;
import xyz.quanguanjia.masterboy.view.MBDActionSheetDialog;


public class MBDEditAvatarActivity extends AppCompatActivity {

    private ImageView avatarImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_avatar);

        //导航栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        MBDToolbarUtils.setCenterTitle(toolbar, "设置头像");
        MBDToolbarUtils.backButtonClicked(toolbar, new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
        MBDToolbarUtils.toolButtonClicked(toolbar, R.id.img_toolbar_more, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MBDEditAvatarActivity.this.showActionSheet();
            }
        });

        Intent intent = getIntent();
        String avatarURL = intent.getStringExtra("imageUrl");

        avatarImageView = findViewById(R.id.image_edit_avatar_ava);

        if (null != avatarURL) {
            String imageUrl = MBDHostManager.IMAGE_HOST + avatarURL;
            MBDImageUtils.imageDBL(imageUrl, avatarImageView);
        }

    }

    private void showActionSheet() {
        MBDActionSheetDialog actionSheetDialog = new MBDActionSheetDialog(this);
        Window window = actionSheetDialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = (int) (DensityUtils.getScreenWidth() * 0.9);
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(layoutParams);
        }
        actionSheetDialog.addMenuItem("拍照").addMenuItem("从手机相册选择");
        actionSheetDialog.setMenuListener(new MBDActionSheetDialog.MenuListener() {
            @Override
            public void onItemSelected(int position, String item) {
                if (0 == position) {
                    MBDEditAvatarActivity.this.takePhoto();
                } else {
                    MBDEditAvatarActivity.this.selectImage();
                }

            }

            @Override
            public void onCancel() {
            }
        });
        actionSheetDialog.show();
    }


    private void takePhoto() {
        PictureSelector pictureSelector = PictureSelector.create(this);
        PictureSelectionCameraModel cameraModel = pictureSelector.openCamera(SelectMimeType.ofImage());
        cameraModel.setCompressEngine(new MBDCompressFileEngine());
        cameraModel.setCropEngine(new MBDCropEngine(this));

        cameraModel.forResult(new OnResultCallbackListener<LocalMedia>() {
            @Override
            public void onResult(ArrayList<LocalMedia> result) {
                assert result.size() > 0;
                LocalMedia media = result.get(0);
                MBDEditAvatarActivity.this.loadImage(media);
                //获取的压缩图片的路径
                uploadAvatar(media.getCutPath());
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void selectImage() {

        PictureSelector pictureSelector = PictureSelector.create(this);

        PictureSelectionSystemModel systemModel = pictureSelector.openSystemGallery(SelectMimeType.ofImage());
        systemModel.setCropEngine(new MBDCropEngine(this));
        systemModel.setCompressEngine(new MBDCompressFileEngine());
        systemModel.forSystemResult(new OnResultCallbackListener<LocalMedia>() {
            @Override
            public void onResult(ArrayList<LocalMedia> result) {
                assert result.size() > 0;

                LocalMedia media = result.get(0);
                MBDEditAvatarActivity.this.loadImage(media);
                uploadAvatar(media.getCutPath());
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void uploadAvatar(String filePath) {
        MBDHttpClient.shared().doPostFileRequest(filePath, null, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {

                if (success && (response.data instanceof String)) {
                    updateUserInfo((String) response.data);
                } else {
                    Toast.makeText(MBDEditAvatarActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void updateUserInfo(String avatarUrl) {
        if (TextUtils.isEmpty(avatarUrl)) {
//            throw new Exception("参数是空");
            return;
        }

        String userId = MBDAccountInfoModel.current().getUserId();
        if (TextUtils.isEmpty(userId)) {
            MBDUserCenter.shared().setToken("");
            MBDAccountInfoModel.clear();
            Toast.makeText(MBDEditAvatarActivity.this, "请重新登录！", Toast.LENGTH_SHORT).show();
            return;
        }

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("avatarUrl", (String) avatarUrl);
        params.put("userId", userId);

        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_USER_UPDATE_INFO, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    Toast.makeText(MBDEditAvatarActivity.this, "更新头像成功！", Toast.LENGTH_SHORT).show();
                    MBDAccountInfoModel.update(true);
                    finish();
                } else {
                    Toast.makeText(MBDEditAvatarActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void loadImage(LocalMedia media) {
        Glide.with(this).load(media.getRealPath()).into(this.avatarImageView); // 加载失败
    }


}
